/**
 * s_time.c
 * time source for TrayInfo.
 * Time support added by Laszlo Ashin <kodest@gmail.com>
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "trayinfo.h"

static char *fmt;

static int
time_write(struct timeval *now, int fd)
{
	char buf[128];
	time_t t;
	struct tm *tmp;
	size_t size;

	t = now->tv_sec;
	tmp = localtime(&t);
	if (!tmp) return 0;
	size = strftime(buf, sizeof(buf), fmt ? fmt : "%m-%d %a %H:%M", tmp);
	fwrite(buf, size, 1, stdout);
	return 1;
}

static void
time_init(void)
{
	fmt = NULL;
}

static void
time_done(void)
{
	if (fmt) free(fmt);
	fmt = NULL;
}

static int
time_cfg_fmt(const char *s)
{
	if (fmt) free(fmt);
	fmt = strdup(s);
	return 0;
}

void
regsrc_time(src_t *src)
{
	src->name = "time";
	src->init = time_init;
	src->done = time_done;
	src->write = time_write;

	cfg_add_handler("time-fmt", time_cfg_fmt);
}
